﻿using System;

class BinToHexDirectly
{
    static void Main()
    {
        string binNum = "011001";
        string hexNum = ConvertHexToBinDirectly(binNum);

        Console.WriteLine("Binary:      " + binNum);
        Console.WriteLine("Hexadecimal: " + hexNum);
    }

    private static string ConvertHexToBinDirectly(string binNum)
    {
        string hexNum = String.Empty;
        int binLen = binNum.Length;

        // Adds leading zeros to make the length divisible by four
        // because each hex digit corresponds to four binary digits
        if (binLen % 4 != 0)
        {
            binNum = new string('0', 4 - (binLen % 4)) + binNum;
        }

        // Takes every four consecutive bits and gives them to GetHexFromBits()
        // to get the corresponding hexadecimal digit
        for (int i = 0; i < binLen; i += 4)
        {
            string fourBits =  binNum.Substring(i, 4);
            hexNum += GetHexFromBits(fourBits);
        }

        return hexNum;
    }

    private static string GetHexFromBits(string hexDigit)
    {
        string bitsFromHex = "";

        switch (hexDigit)
        {
            case "0000":
                bitsFromHex = "0";
                break;
            case "0001":
                bitsFromHex = "1";
                break;
            case "0010":
                bitsFromHex = "2";
                break;
            case "0011":
                bitsFromHex = "3";
                break;
            case "0100":
                bitsFromHex = "4";
                break;
            case "0101":
                bitsFromHex = "5";
                break;
            case "0110":
                bitsFromHex = "6";
                break;
            case "0111":
                bitsFromHex = "7";
                break;
            case "1000":
                bitsFromHex = "8";
                break;
            case "1001":
                bitsFromHex = "9";
                break;
            case "1010":
                bitsFromHex = "A";
                break;
            case "1011":
                bitsFromHex = "B";
                break;
            case "1100":
                bitsFromHex = "C";
                break;
            case "1101":
                bitsFromHex = "D";
                break;
            case "1110":
                bitsFromHex = "E";
                break;
            case "1111":
                bitsFromHex = "F";
                break;
        }

        return bitsFromHex;
    }
}
